package cn.com.demo.config;

import io.jsonwebtoken.*;
import io.jsonwebtoken.impl.compression.GzipCompressionCodec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MyTokenConfig {
    @Autowired
    TokenConfigProperties tokenConfigProperties;
    public String getToken(String userName) {
        return Jwts.builder()
                .setSubject(userName)
                .setExpiration(new Date(System.currentTimeMillis() + tokenConfigProperties.getExpireTime()*1000))
                .signWith(SignatureAlgorithm.HS512,tokenConfigProperties.getSignKey())
                .compressWith(new GzipCompressionCodec()).compact();
    }
    public String getUserName(String token) {
        try {
            return Jwts.parser().setSigningKey(tokenConfigProperties.getSignKey()).parseClaimsJws(token).getBody().getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("token 解析异常");
        }
        return null;
    }
    public TokenConfigProperties getTokenConfigProperties(){
        return tokenConfigProperties;
    }
}
